/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MessageIO;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * MessageServer is multithreaded.  It uses sockets and packet-based chat.
 * @author Mark
 */
public class MessengerServer implements MessageListener
    {
    private ExecutorService serverEx;//executor for server
    private ArrayList<ChatUsername> userNames;
    private String logname;
    private FileOutputStream log;
    private PrintStream serverLogger;

    /**
     * Createsa MessengerServer
     */
    public MessengerServer()
        {
        super();
        try
            {
            serverEx = Executors.newCachedThreadPool();
            userNames = new ArrayList<ChatUsername>();
            logname = "serverlog.txt";
            log = new FileOutputStream(logname, true);
            serverLogger = new PrintStream(log);
            serverLogger.println("Log started " + new Date());
            }
        catch (FileNotFoundException ex)
            {
            ex.printStackTrace();
            }
        }
    /**
     * Starts the chat server
     */
    public void startServer()
        {
        ServerSocket socket = null;
        try
            {
            socket = new ServerSocket(SocketConstants.SERVER_PORT);
            //socket used for incoming
            System.out.println("Listening to port " + SocketConstants.SERVER_PORT);
            while (true)//always listens
                {
                Socket client = socket.accept();//accepts client
                serverEx.execute(new MessageReceiver(this, client, userNames));
                //creates a MessageReceiver to accept messages
                System.out.println("Connection with " + client.getInetAddress());
                }
            }
        catch (IOException io)
            {
            io.printStackTrace();
            }
        }

    /**
     * broadcasts message to clients when a new message is received
     * @param from userName
     * @param message message contents
     */
    public void messageReceived(String from, String message)
        {
        String completeMessage = from + "("
                    + new Date().toString().substring(11,19) + ")"
                    +SocketConstants.MESSAGE_SEPERATOR + " " + message;
        serverEx.execute(new MulticastSender((from +
                SocketConstants.MESSAGE_SEPERATOR + message).getBytes()));
        System.out.println(completeMessage);//Server sees everything
        serverLogger.println(completeMessage);//Server records everthing
        }


    }
